// 2.1 获取控制台
use reqwest::Client;
use anyhow::{anyhow, Result};
use crate::api::get_xsts::get_xsts_web_token;
use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
struct XboxResponse {
    status: Status,
    result: Vec<Console>,
    agentUserId: Option<String> // 使用Option处理null
}

#[derive(Debug, Serialize, Deserialize)]
struct Status {
    errorCode: String,
    errorMessage: Option<String> // 使用Option处理null
}
/** 示例
 * {
      id: 'F4001D0F950AA28A',
      name: '客厅 Xbox',
      locale: 'zh-Hans-SG',
      powerState: 'ConnectedStandby',
      consoleType: 'XboxSeriesS'
    }
 */
#[derive(Debug, Serialize, Deserialize)]
pub struct Console{
    pub id: String,
    pub name: String,
    pub locale: String,
    pub powerState: String,
    pub consoleType: String,
}

/* 返回控制台列表 */
pub async fn get_console() -> Result<Vec<Console>> {
    let client = Client::new();
    let uhs = get_xsts_web_token().await.unwrap().uhs;
    let web_token = get_xsts_web_token().await.unwrap().web_token;
    let Authorization = format!("XBL3.0 x={};{}", uhs, web_token);
    let response = client.get("https://xccs.xboxlive.com/lists/devices?queryCurrentDevice=false&includeStorageDevices=true")
        .header("Authorization", Authorization)
        .header("Accept-Language", "en-US")
        .header("x-xbl-contract-version", "2")
        .header("x-xbl-client-name", "XboxApp")
        .header("x-xbl-client-type", "UWA")
        .header("x-xbl-client-version", "39.39.22001.0")
        .send().await.unwrap();
    let response_code = response.status().as_u16();
    let response_text = response.text().await.unwrap();
    match response_code {
        200 =>{
            let response: XboxResponse = serde_json::from_str(&response_text)?;
            return Ok(response.result);
        }
        _ =>{
            return Err(anyhow!("failed to get console, response code: {response_code}"));
        }
    }
}